<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;


class RoleController extends BaseController
{
    protected $api_url = [
        'index' => ['get', 'role'],
        'show' => ['get', 'role/%d'],
        'store' => ['post', 'role'],
        'update' => ['put', 'role/%d'],
        'destroy' => ['delete', 'role/%d'],
        'menu' => ['get', 'menu_all'],
        'menu_per' => ['get', 'menu_per'],
        'action_per' => ['post', 'action_per'],
        'permission_role' => ['get', 'role/permission_role/%d'],

    ];

    public function index(Request $request)
    {
        $res = http_admin($this->api_url['index'])->send(['page' => $request->input('page', 1)]);
        $data = paginate($request, $res['data']);
        return view('Admin.role.index', $data);
    }

    public function edit($id)
    {
        $res = http_admin($this->api_url['show'], [$id])->send();
        $role_id=$res['data']['role_id'];
        $permission = http_admin($this->api_url['permission_role'], [$role_id])->send();
        $menu = http_admin($this->api_url['menu'])->send();
        $tree = list_to_tree(array_get($menu,'data',[]),'menu_id','parent_id');
        $res['data']['menu']=$tree;
        $res['data']['permission']=$permission['data'];
        Cookie::queue('role_per_data',serialize($permission['data']));

        return view('Admin.role.edit', $res['data']);
    }


    public function create()
    {
        $res = http_admin($this->api_url['menu'])->send();
        $tree = list_to_tree(array_get($res,'data',[]),'menu_id','parent_id');
        $res['data']=$tree;
        return view('Admin.role.create',$res);
    }

    public function store(Request $request)
    {
        $data = $request->except('_token', '_method');
        $res = http_admin($this->api_url['store'])->send($data);

//        $data['role_id']=$res['data']['role_id'];
//        $pre_menu = http_admin($this->api_url['menu_per'])->send($data);
//        $pre_atc = http_admin($this->api_url['action_per'])->send($data);
        return redirect('/foradmin/role');
    }

    public function update($id, Request $request)
    {
        $data = $request->except('_token', '_method');
        $role_per_data=$request->cookie('role_per_data');
        $roler_per_old=unserialize($role_per_data);

        $data['old_permission']=$roler_per_old;
        $res = http_admin($this->api_url['update'], [$id])->send($data);
        return redirect('/foradmin/role');

    }

    public function destroy($id)
    {
        $res = http_admin($this->api_url['destroy'], [$id])->send();

        return redirect('/foradmin/role');
    }
}
